<template>
  <div class="math-formula-editor">
    <div class="editor-header">
      <h3>数学公式编辑器</h3>
      <el-tooltip content="关闭" placement="top">
        <el-button @click="$emit('close')" circle>
          <el-icon><Close /></el-icon>
        </el-button>
      </el-tooltip>
    </div>
    
    <div class="editor-body">
      <div class="input-area">
        <el-input
          v-model="latexCode"
          type="textarea"
          :rows="5"
          placeholder="请输入LaTeX公式代码，例如：E = mc^2"
          @input="renderFormula"
        />
      </div>
      
      <div class="preview-area">
        <div class="preview-title">预览</div>
        <div class="formula-preview" ref="previewEl"></div>
      </div>
      
      <div class="common-formulas">
        <div class="section-title">常用公式</div>
        <div class="formula-buttons">
          <el-button 
            v-for="(formula, index) in commonFormulas" 
            :key="index"
            size="small"
            @click="insertFormula(formula.code)"
          >
            {{ formula.name }}
          </el-button>
        </div>
      </div>
    </div>
    
    <div class="editor-footer">
      <el-button @click="$emit('close')">取消</el-button>
      <el-button type="primary" @click="confirmFormula">确认</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { Close } from '@element-plus/icons-vue'
import katex from 'katex'
import 'katex/dist/katex.min.css'

// 定义props
const props = defineProps({
  initialFormula: {
    type: String,
    default: ''
  }
})

// 定义emit事件
const emit = defineEmits(['close', 'confirm'])

// LaTeX代码
const latexCode = ref(props.initialFormula || '')

// 预览元素引用
const previewEl = ref(null)

// 常用公式列表
const commonFormulas = [
  { name: '分数', code: '\\frac{a}{b}' },
  { name: '平方根', code: '\\sqrt{x}' },
  { name: 'n次方根', code: '\\sqrt[n]{x}' },
  { name: '上标', code: 'x^{n}' },
  { name: '下标', code: 'x_{i}' },
  { name: '积分', code: '\\int_{a}^{b} f(x) \\, dx' },
  { name: '求和', code: '\\sum_{i=1}^{n} x_i' },
  { name: '极限', code: '\\lim_{x \\to 0} f(x)' },
  { name: '矩阵', code: '\\begin{pmatrix} a & b \\\\ c & d \\end{pmatrix}' },
  { name: '希腊字母α', code: '\\alpha' },
  { name: '希腊字母β', code: '\\beta' },
  { name: '希腊字母γ', code: '\\gamma' },
  { name: '希腊字母π', code: '\\pi' },
  { name: '无穷', code: '\\infty' },
  { name: '属于', code: '\\in' },
  { name: '不等式', code: 'a \\neq b' },
  { name: '约等于', code: 'a \\approx b' },
  { name: '大于等于', code: 'a \\geq b' },
  { name: '小于等于', code: 'a \\leq b' },
]

// 渲染公式
const renderFormula = () => {
  if (!previewEl.value) return
  
  try {
    // 预处理LaTeX代码，去除不兼容的Unicode字符
    const sanitizedLatexCode = latexCode.value.replace(/[^\x00-\x7F]/g, '');
    
    // 使用KaTeX渲染公式
    katex.render(sanitizedLatexCode || '预览区域', previewEl.value, {
      throwOnError: false,
      displayMode: true,
      strict: 'ignore'
    })
  } catch (error) {
    console.error('渲染公式出错:', error)
    previewEl.value.textContent = '公式格式有误，请检查'
  }
}

// 插入公式
const insertFormula = (formulaCode) => {
  // 获取当前光标位置
  const textarea = document.querySelector('.math-formula-editor .el-textarea__inner')
  const start = textarea.selectionStart
  const end = textarea.selectionEnd
  
  // 在光标位置插入公式代码
  latexCode.value = latexCode.value.substring(0, start) + formulaCode + latexCode.value.substring(end)
  
  // 重新渲染公式
  renderFormula()
  
  // 聚焦回文本框并将光标移动到插入的公式代码之后
  setTimeout(() => {
    textarea.focus()
    const newPosition = start + formulaCode.length
    textarea.setSelectionRange(newPosition, newPosition)
  }, 0)
}

// 确认公式
const confirmFormula = () => {
  emit('confirm', latexCode.value)
}

// 监听公式代码变化，自动渲染
watch(latexCode, renderFormula)

// 组件挂载时初始化渲染
onMounted(() => {
  renderFormula()
})
</script>

<style scoped>
.math-formula-editor {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

.editor-header h3 {
  margin: 0;
}

.editor-body {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.input-area {
  width: 100%;
}

.preview-area {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 16px;
  min-height: 100px;
  background-color: #f5f7fa;
}

.preview-title {
  font-weight: bold;
  margin-bottom: 8px;
  color: #606266;
}

.formula-preview {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 60px;
}

.common-formulas {
  margin-top: 16px;
}

.section-title {
  font-weight: bold;
  margin-bottom: 8px;
  color: #606266;
}

.formula-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.editor-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 16px;
  border-top: 1px solid #ebeef5;
  padding-top: 16px;
}
</style>